<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑公告' : '新增公告'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="公告标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入公告标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="公告类型" prop="type">
            <el-select
              v-model="formData.type"
              placeholder="请选择公告类型"
              style="width: 100%"
            >
              <el-option
                v-for="option in utils.getTypeOptions()"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公告级别" prop="level">
            <el-select
              v-model="formData.level"
              placeholder="请选择公告级别"
              style="width: 100%"
            >
              <el-option
                v-for="option in utils.getLevelOptions()"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标受众" prop="targetAudience">
            <el-select
              v-model="formData.targetAudience"
              placeholder="请选择目标受众"
              style="width: 100%"
            >
              <el-option
                v-for="option in utils.getTargetAudienceOptions()"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
              v-model="formData.publishTime"
              type="datetime"
              placeholder="请选择发布时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过期时间" prop="expireTime">
            <el-date-picker
              v-model="formData.expireTime"
              type="datetime"
              placeholder="请选择过期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="公告状态" prop="status">
            <el-select
              v-model="formData.status"
              placeholder="请选择公告状态"
              style="width: 100%"
            >
              <el-option
                v-for="option in utils.getStatusOptions()"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否置顶">
            <el-switch
              v-model="formData.isTop"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否弹窗">
            <el-switch
              v-model="formData.isPopup"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="formData.content"
              type="textarea"
              placeholder="请输入公告内容"
              :rows="8"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  createAnnouncementApi,
  updateAnnouncementApi,
  AnnouncementManagementUtils,
  AnnouncementStatus,
  type AnnouncementInfo,
  type CreateAnnouncementRequest
} from "@/api/announcement-management";

// 将工具类暴露给模板
const utils = AnnouncementManagementUtils;

// Props
interface Props {
  visible: boolean;
  announcement?: AnnouncementInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  announcement: null
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  success: [];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const submitLoading = ref(false);

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const isEdit = computed(() => !!props.announcement);

// 表单数据
const formData = reactive<CreateAnnouncementRequest>({
  title: "",
  content: "",
  type: 1,
  level: 1,
  status: AnnouncementStatus.DRAFT,
  isTop: 0,
  isPopup: 0,
  targetAudience: "all",
  publishTime: "",
  expireTime: ""
});

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    title: "",
    content: "",
    type: 1,
    level: 1,
    status: AnnouncementStatus.DRAFT,
    isTop: 0,
    isPopup: 0,
    targetAudience: "all",
    publishTime: "",
    expireTime: ""
  });
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 监听公告数据变化
watch(
  () => props.announcement,
  newVal => {
    if (newVal) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        title: newVal.title,
        content: newVal.content,
        type: newVal.type,
        level: newVal.level,
        status: newVal.status,
        isTop: newVal.isTop,
        isPopup: newVal.isPopup,
        targetAudience: newVal.targetAudience,
        publishTime: newVal.publishTime,
        expireTime: newVal.expireTime
      });
    } else {
      // 新增模式，重置表单
      resetForm();
    }
  },
  { immediate: true }
);

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: "请输入公告标题", trigger: "blur" },
    { min: 1, max: 100, message: "标题长度在1到100个字符", trigger: "blur" }
  ],
  content: [
    { required: true, message: "请输入公告内容", trigger: "blur" },
    { min: 1, max: 2000, message: "内容长度在1到2000个字符", trigger: "blur" }
  ],
  type: [{ required: true, message: "请选择公告类型", trigger: "change" }],
  level: [{ required: true, message: "请选择公告级别", trigger: "change" }],
  status: [{ required: true, message: "请选择公告状态", trigger: "change" }],
  targetAudience: [
    { required: true, message: "请选择目标受众", trigger: "change" }
  ],
  publishTime: [
    { required: true, message: "请选择发布时间", trigger: "change" }
  ],
  expireTime: [
    { required: true, message: "请选择过期时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && formData.publishTime) {
          if (new Date(value) <= new Date(formData.publishTime)) {
            callback(new Error("过期时间必须晚于发布时间"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    let response;
    if (isEdit.value && props.announcement) {
      // 编辑模式
      response = await updateAnnouncementApi({
        ...formData,
        id: props.announcement.id
      });
    } else {
      // 新增模式
      response = await createAnnouncementApi(formData);
    }

    if (response && response.code === 200) {
      ElMessage.success(isEdit.value ? "编辑成功" : "创建成功");
      emit("success");
    }
  } catch (error: any) {
    console.error("提交失败:", error);
    ElMessage.error(`提交失败: ${error?.message || "未知错误"}`);
  } finally {
    submitLoading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
